#include "qtemplatedialog.h"
#include "ui_qtemplatedialog.h"

#include "qtemplatetreewidget.h"
#include "qformwidget.h"

#include "../../libs/sharedLib/qnamevalidator.h"
#include "../../libs/sharedLib/qpagemanager.h"
#include "../../libs/sharedLib/qpageinfo.h"
#include "../../libs/sharedLib/qprojectcore.h"
#include "../../libs/sharedLib/xml.h"
#include "../../libs/coreLib/minisplitter.h"

#include <QDir>
#include <QApplication>
#include <QXmlStreamReader>
#include <QFileDialog>

QTemplateDialog::QTemplateDialog(const QString& type,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::QTemplateDialog),
    m_nameEdit(new SHAREDLIB::QNameEdit("[_a-zA-Z][_a-zA-Z0-9]{,64}")),
    m_treelist(new QTemplateTreeWidget(this)),
    m_templateInfo(NULL),
    m_type(type)
{
    ui->setupUi(this);
    ui->horizontalLayout_3->addWidget(m_nameEdit,1);

    CORELIB::MiniSplitter *splitter=new CORELIB::MiniSplitter(this);

    splitter->addWidget(m_treelist);

    QWidget* wid=new QWidget;
    wid->setLayout(ui->verticalLayout);
    splitter->addWidget(wid);

    splitter->setStretchFactor(0,0);
    splitter->setStretchFactor(1,1);

    m_treelist->setMinimumSize(200,200);
    m_treelist->resize(200,200);
    m_treelist->setFrameStyle(QFrame::NoFrame);
    m_treelist->set_base_path(qApp->applicationDirPath()+"/template/"+m_type+"/");

    QVBoxLayout *v=new QVBoxLayout;
    v->setMargin(0);
    v->setSpacing(0);
    v->addWidget(splitter);
    this->setLayout(v);

    SHAREDLIB::QPageManager *p=SHAREDLIB::QProjectCore::getCore()->pageManager();

    QList<SHAREDLIB::QPageInfo*> list=p->getPages(type);
    QStringList l;
    foreach(SHAREDLIB::QPageInfo* info,list)
    {
        l.append(info->get_name());
    }
    m_nameEdit->setIntermediateList(l);

    m_nameEdit->setProperty("no-ManhattanStyle",true);
    m_nameEdit->setFocus();

    connect(m_treelist,SIGNAL(select(tagTemplateInfo*)),this,SLOT(select(tagTemplateInfo*)));


    QString path=qApp->applicationDirPath()+"/template/"+type;

    QDir dir(path);

    QList<QFileInfo> fileinfo=dir.entryInfoList();
    QString str;
    foreach(QFileInfo info,fileinfo)
    {
        if(info.isFile())
        {
            str=info.fileName();
            if(str.endsWith(".xml"))
            {
                QFile f(info.filePath());
                if(f.open(QFile::ReadOnly))
                {
                    QString buff=f.readAll();
                    SHAREDLIB::XMLObject xml;
                    if(xml.read(buff))
                    {
                        QFormWidget *wid=new QFormWidget(type,this);
                        wid->setProperty("grab","true");
                        wid->load(buff,"");
                        wid->setVisible(false);
                        str=str.left(str.size()-4);
                        QPixmap widgetPixmap = QPixmap::grabWidget(wid);
                        QSize sz=widgetPixmap.size();
                        if(sz.width()>400)
                        {
                            sz.setWidth(400);
                        }
                        else if(sz.width()<160)
                        {
                            sz.setWidth(160);
                        }
                        if(sz.height()>300)
                        {
                            sz.setHeight(300);
                        }
                        else if(sz.height()<160)
                        {
                            sz.setHeight(160);
                        }
                        widgetPixmap=widgetPixmap.scaled(sz,Qt::KeepAspectRatio,Qt::SmoothTransformation);
                        m_images.insert(info.filePath(),widgetPixmap);
                        m_treelist->add_default_item(info.filePath(),str);
                    }
                }
            }
        }
    }

    connect(m_treelist,SIGNAL(remove_signal(QString)),this,SLOT(remove(QString)));
    connect(m_treelist,SIGNAL(changed(QString,QString)),this,SLOT(changed(QString,QString)));
}

QTemplateDialog::~QTemplateDialog()
{
    delete ui;
}

void QTemplateDialog::select(tagTemplateInfo *info)
{
    if(info!=NULL)
    {
        m_templateInfo=info;
        QPixmap pixmap=m_images.value(info->m_file_name);

        ui->pixmap_view->setPixmap(pixmap);
        ui->pixmap_view->setFixedSize(pixmap.size());
        m_nameEdit->setValue(info->m_name);
        m_template_name=info->m_file_name;
    }
    else
    {
        ui->pixmap_view->setPixmap(QPixmap());
        m_nameEdit->setValue("");
        m_template_name="";
    }

}

void QTemplateDialog::on_exists_button_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                     QDir::currentPath(),
                                                     tr("Page File (*.xml)"));

    if(fileName!=NULL)
    {
        QFile f(fileName);
        if(f.open(QFile::ReadOnly))
        {
            QString buff=f.readAll();
            SHAREDLIB::XMLObject xml;
            if(xml.read(buff))
            {
                QFormWidget *wid=new QFormWidget(m_type,this);
                wid->setProperty("grab","true");
                wid->load(buff,"");
                wid->setVisible(false);
                QString str=fileName.mid(fileName.lastIndexOf("/")+1);
                str=str.left(str.size()-4);
                QPixmap widgetPixmap = QPixmap::grabWidget(wid);
                QSize sz=widgetPixmap.size();
                if(sz.width()>400)
                {
                    sz.setWidth(400);
                }
                else if(sz.width()<160)
                {
                    sz.setWidth(160);
                }
                if(sz.height()>300)
                {
                    sz.setHeight(300);
                }
                else if(sz.height()<160)
                {
                    sz.setHeight(160);
                }
                widgetPixmap=widgetPixmap.scaled(sz,Qt::KeepAspectRatio,Qt::SmoothTransformation);
                m_images.insert(fileName,widgetPixmap);
                m_treelist->add_more_item(fileName,str);
            }
        }
    }
}

void QTemplateDialog::remove(const QString &path)
{
    m_images.remove(path);
}

void QTemplateDialog::changed(const QString &old, const QString &now)
{
    QPixmap p=m_images.value(old);
    m_images.remove(old);
    m_images.insert(now,p);
}

void QTemplateDialog::on_okbtn_clicked()
{
    QString str=m_nameEdit->value();
    if(str=="")
    {
        return;
    }

    m_name=str;
    close();
}

void QTemplateDialog::on_cancelbtn_clicked()
{
    close();
}

QString QTemplateDialog::get_name()
{
    return m_name;
}

QString QTemplateDialog::get_template_name()
{
    return m_template_name;
}
